package com.kklsqm.langchain4j.controller;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;

/**
 * 功能:
 * 作者: 沙琪马
 * 日期: 2025/4/23 15:23
 */
@RestController
public class Mp3Controller {

    @GetMapping("/download-mp3")
    public void downloadMp3(HttpServletResponse response) throws IOException {
        // 读取Hex编码数据文件
        File hexFile = new File("data.hex");  // 假设data.hex文件与Spring Boot项目在同一目录下
        String hexData = new String(Files.readAllBytes(hexFile.toPath()));

        // 将Hex编码转换为二进制数据
        byte[] mp3Data = hexStringToByteArray(hexData);

        // 创建MP3文件
        File mp3File = new File("output.mp3");
        try (FileOutputStream fos = new FileOutputStream(mp3File)) {
            fos.write(mp3Data);
        }

        // 设置响应头，指示文件下载
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=output.mp3");
        response.setStatus(HttpStatus.OK.value());

        // 将文件写入响应
        Files.copy(mp3File.toPath(), response.getOutputStream());
        response.getOutputStream().flush();
    }

    // 将Hex编码转换为字节数组
    private byte[] hexStringToByteArray(String hexString) {
        int length = hexString.length();
        byte[] byteArray = new byte[length / 2];
        for (int i = 0; i < length; i += 2) {
            byteArray[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                    + Character.digit(hexString.charAt(i + 1), 16));
        }
        return byteArray;
    }
}
